<template>
  <view class="page" >
    <div style="margin-bottom: 650px">
      <nut-cell class="top-cell" >
        <nut-space direction="vertical" fill>
          <!-- AQI等级展示 -->
          <nut-cell class="card" round-radius="18px">
            <nut-space direction="vertical">
              <div>AQI等级指数</div>
              <nut-cell title="[优] 空气质量令人满意，基本无空气污染" style="background-color: #5FB878;font-size: 13px;margin-bottom: 0;margin-top:0;height: 20px;text-align: left;padding: 0 10px;color: #fff;" >
              </nut-cell>
              <nut-cell title="[良] 空气质量可接受，但某些污染物可能对极少数异常敏感人群健康有较弱影响" style="background-color: #99D66C;font-size: 13px;margin-bottom: 0;margin-top:0;height: 40px;text-align: left;padding: 0 10px;color: #fff;" >
              </nut-cell>
              <nut-cell title="[轻度污染] 易感人群症状有轻度加剧，健康人群出现刺激症状" style="background-color: #F1E676;font-size: 13px;margin-bottom: 0;margin-top:0;height: 40px;text-align: left;padding: 0 10px;color: #fff;">
              </nut-cell>
              <nut-cell title="[中度污染]	进一步加剧易感人群症状，可能对健康人群心脏、呼吸系统有影响" style="background-color: #DA796F;font-size: 13px;margin-bottom: 0;margin-top:0;height: 40px;text-align: left;padding: 0 10px;color: #fff;">
              </nut-cell>
              <nut-cell title="[重度污染] 心脏病和肺病患者症状显著加剧，运动耐受力降低，健康人群普遍出现症状" style="background-color: #A23BB9;font-size: 13px;margin-bottom: 0;margin-top:0;height: 40px;text-align: left;padding: 0 10px;color: #fff;">
              </nut-cell>
              <nut-cell title="[严重污染] 健康人群运动耐受力降低，有明显强烈症状，提前出现某些疾病" style="background-color: #581845 ;font-size: 13px;margin-bottom: 0;margin-top:0;height: 40px;text-align: left;padding: 0 10px;color: #fff;">
              </nut-cell>
            </nut-space>
          </nut-cell>
          <!-- 省市  -->
          <nut-cell title="选择反馈省市" :desc="text" is-link @click="showAddress" style="margin-top: 0;margin-bottom: 0"></nut-cell>
            <nut-address
              v-model:visible="showPopup"
              :province="getProvince()"
              :city="cities"
              @change="onChange"
              @close="close"
              custom-address-title="请选择所在地区"
            ></nut-address>
            <!-- 地址 -->
            <nut-cell style="margin-top: 0;margin-bottom: 0" >
              <nut-space direction="vertical">
                <div>请输入详细地址:</div>
                <nut-input v-model="addressInput"  style="margin-top: 0; width: 250px;"/>
              </nut-space>
            </nut-cell>
            <!-- 空气质量等级 -->
            <nut-cell style="margin-top: 0;margin-bottom: 0">
              <nut-space direction="vertical">
                <div>空气质量指数等级：{{ aqiLevelDesc }}</div>
                <nut-rate v-model="aqiLevel" :active-color="aqiColor" :count="6" @change="onAqiChange" />
              </nut-space>
            </nut-cell>
            <!-- 反馈详情 -->
            <nut-cell style="margin-top: 0;margin-bottom: 0">
              <nut-space direction="vertical">
                <div>请输入反馈详情:</div>
                <nut-input v-model="feedbackInfoInput"  style="margin-bottom:0;width: 250px;"/>
              </nut-space>
            </nut-cell>
            <!-- 上传图片 -->
            <nut-cell style="margin-top: 0;margin-bottom: 0;height: 160px;">
              <nut-space direction="vertical">
                <nut-row style="width: 250px;">
                  <nut-col :span="12"><div style="margin-left: 0">上传详情图片</div></nut-col>
                  <nut-col :span="12" v-show="isShowUploadProgress"><nut-progress :percentage="progressPercent" style="margin-top: 3px;" stroke-color="#a3d182" text-color="#a3d182"></nut-progress></nut-col>
                </nut-row>
                <nut-uploader :before-xhr-upload="beforeXhrUpload" :auto-upload="false" ref="uploadRef"  maximum="2" @delete="handleDelete" :is-deletable="!isShowUploadProgress" style="margin-top: 0"></nut-uploader>
              </nut-space>
            </nut-cell>
          <!-- 提交按钮 -->
          <nut-button @click="submitFeedback" size="normal" block type="info" style="height:40px ;--nut-button-large-font-size:20px ; margin-bottom:0" color="linear-gradient( 135deg, #C9F2A5 10%, #52BF4E 100%)">提交反馈</nut-button>
        </nut-space>
      </nut-cell> 
    </div>
    <CustomTabBar />
  </view>
</template>

<script setup lang="ts">
import './index.scss'
import Counter from '../../components/Counter.vue'
import Taro from '@tarojs/taro'
import CustomTabBar from '../../CustomTabBar/index.vue'
import { ref , reactive, onMounted} from 'vue'
import {
  provinceAndCityData,
} from "element-china-area-data";
import  feedbackApi  from '../../api/feedback'
import { aqiFeedbackType } from 'src/stores/types'
import { useCounterStore } from '../../stores/counter'


const progressPercent = ref(0)
const isShowUploadProgress = ref(false)
const aqiLevelDesc = ref('')
const aqiLevel = ref(0)
const aqiColor = ref('#5FB878')
const feedbackInfoInput = ref('')
const addressInput = ref('')
const showPopup = ref(false)
const address = reactive({
  provinceAndCityData,
})
const cities = ref([])
const text = ref('选择地址')
const province = ref<{name: string , id: number}>({name: '', id: 0})
const city = ref<{name: string , id: number}>({name: '', id: 0})
const fbImg = ref<string>('')

//空气质量等级选择
const onAqiChange = (val: number) => {
  switch (val) {
    case 6:
      aqiColor.value = '#5FB878'
      aqiLevelDesc.value = '[优]'
      break 
    case 5:
      aqiColor.value = '#99D66C'
      aqiLevelDesc.value = '[良]'
      break
    case 4:
      aqiColor.value = '#F1E676'
      aqiLevelDesc.value = '[轻度污染]'
      break
    case 3:
      aqiColor.value = '#DA796F'
      aqiLevelDesc.value = '[中度污染]'
      break
    case 2:
      aqiColor.value = '#A23BB9'
      aqiLevelDesc.value = '[重度污染]'
      break
    case 1:
      aqiColor.value = '#581845'
      aqiLevelDesc.value = '[严重污染]'
      break
  }
}
//地址选择框配置
const showAddress = () => {
  showPopup.value = !showPopup.value
}
//获取省份信息
function getProvince(){
  let province = []
  for(let i = 0;i<address.provinceAndCityData.length;i++){
    province.push({
      name:address.provinceAndCityData[i].label,
      id:address.provinceAndCityData[i].value,
      index:i
    })
  }
  return province
}
//选中省份后加载城市信息
const onChange = (cal) => {
  if(provinceAndCityData[cal.value.index]?.children){
    cities.value = []
    for(let i = 0;i<address.provinceAndCityData[cal.value.index].children?.length;i++){
      cities.value.push({
        name:address.provinceAndCityData[cal.value.index].children[i].label,
        id:address.provinceAndCityData[cal.value.index].children[i].value,
      })
    }
  }
}
//关闭地址选择框显示选中省市信息
const close = (val) => {
  text.value = val.data.addressStr
  console.log(val)
  province.value = val.data.province
  city.value = val.data.city
}

//提交反馈信息
const submitFeedback = async () => {
  //上传图片
  await submitUpload()
  //获取反馈信息
  let feedbackInfo: aqiFeedbackType = {
    fbId: 0,
    monId: 1,
    fbInfo: feedbackInfoInput.value,
    fbAqiLevel: aqiLevel.value,
    fbTime: Date.now().toString(),
    fbImg: fbImg.value,
    fbAssignState: 0,
    fbAssignTime: '',
    provinceId: province.value.id,
    cityId: city.value.id,
    fbAddress: addressInput.value,
    remarks: ''
  }
  //提交反馈信息
  await feedbackApi.createAqiFeedback(feedbackInfo).then(res => {
    if(res.data.code === 200){ //反馈成功
      Taro.showToast({
        title: '反馈成功',
        duration: 3000,
        mask: true
      })
      setTimeout(() => {
        Taro.switchTab({
          url: '/pages/index/index'
        })
        useCounterStore().tabIndex = 0
      }, 2000)
    }else{
      Taro.showToast({
      title: '反馈失败,请稍后再试',
      icon: 'none',
      duration: 2000,
      mask: true  
    })
    }
  })
  //向数据库中添加省市信息
  await feedbackApi.addProvinceAndCity({
      provinceId: province.value.id, 
      provinceName: province.value.name, 
      cityId: city.value.id, 
      cityName: city.value.name})
  .then(res => {
      if(res.data.code !== 200){
        //todo 提示失败信息
      }
  })
}

const uploadRef = ref(null)
const submitUpload = async () => {
  if(uploadRef.value){
    await uploadRef.value.submit()
  }
}

//删除图片
const handleDelete = (file) => {
  console.log(file)
}

function updatefbImg(imgUrl: string){
  fbImg.value = fbImg.value + 'http://sffwuytfo.hb-bkt.clouddn.com/' + imgUrl + '@::@'
} 

//上传图片
const beforeXhrUpload = async (taroUploadFile, options ) => {
      let token = '';
      let fileName = 'mon-1-'+Date.now().toString()+'.png';
      await feedbackApi.getUploadToken(fileName).then( async res =>  {
        if(res.data.code === 200){
          token = res.data.data;
          //上传文件
          const uploadTask = taroUploadFile({
            url: "https://upload-z1.qiniup.com",
            filePath: options.taroFilePath,
            fileType: options.fileType,
            header: {
              'Content-Type': 'multipart/form-data',
            }, 
            formData: {
              //"token": "QN0j98Ubf2z4EmJifmyH2HkY1mITL080OEKfSat6:NAOVJ0X3Pn-dYYMb76Q9lymhKbc=:eyJzY29wZSI6ImVwLW1vbm90b3Jpbmctc3lzOnRlc3QucG5nIiwiZGVhZGxpbmUiOjE3MjEyNDMxMTd9",
              "token" : token,
              "key": fileName,
            },
            name: options.name,
            success(response: { errMsg; statusCode; data }) {
              if (options.xhrState == response.statusCode) {
                options.onSuccess?.(response, options);
              } else {
                options.onFailure?.(response, options);
              }
            },
            fail(e) {
              options.onFailure?.(e, options);
            }
          });
          options.onStart?.(options);
          //上传进度
          await uploadTask.progress((res) => {
            isShowUploadProgress.value = true;
            progressPercent.value = res.progress;
          }).then(() => {
            //关闭上传进度条
            isShowUploadProgress.value = false;
            progressPercent.value = 0;
            //更新图片信息
            updatefbImg(fileName)
            });
        }else{
          Taro.showToast({
            title: '获取上传token失败,请检查权限稍后再试',
            icon: 'none',  
            duration: 3000,
            mask: true  
          })
        }
      });
    };
</script>

<style>
.top-cell{
    margin-top: 0;
    --nut-cell-large-padding:25px;
  
    background-image: linear-gradient( 135deg, #C9F2A5 10%, #52BF4E 100%);
  
    width:100%;
    height:600px;
    border-bottom-left-radius:60%;
    border-bottom-right-radius:60%;
    }

    .card{
    margin-top: 10%;
    height: 620px;
    }

</style>
